package com.jeeww.web.admin.service.usermanage.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jeeww.core.service.impl.BaseServiceImpl;
import com.jeeww.core.syspojo.AgtbOrganizationInfo;
import com.jeeww.core.syspojo.AgtbOrganizationInfoDAO;
import com.jeeww.core.syspojo.AgtbRoleInfo;
import com.jeeww.core.syspojo.AgtbRoleInfoDAO;
import com.jeeww.core.syspojo.AgtbUserConfigrationInfo;
import com.jeeww.core.syspojo.AgtbUserConfigrationInfoDAO;
import com.jeeww.core.syspojo.AgtbUserInfo;
import com.jeeww.core.syspojo.AgtbUserInfoDAO;
import com.jeeww.core.syspojo.AgtbUserRoleRel;
import com.jeeww.core.syspojo.AgtbUserRoleRelDAO;
import com.jeeww.core.syspojo.AgtbUserRoleRelId;
import com.jeeww.core.utils.AgileUtils;
import com.jeeww.core.utils.BeanUtilsEx;
import com.jeeww.core.utils.JsonUtils;
import com.jeeww.core.vo.Pager;
import com.jeeww.utils.UserDetailUtils;
import com.jeeww.web.admin.dto.usermanage.UserManageDTO;
import com.jeeww.web.admin.searchmodel.usermanage.UserManageSearchModel;
import com.jeeww.web.admin.service.usermanage.UserManagerService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 类描述：接口.
 * @author 蒋文武
 */
@Service("UserManagerServiceImpl")
public class UserManagerServiceImpl extends BaseServiceImpl implements UserManagerService {
    /**
     * logger.
     */
    private Logger logger = Logger.getLogger(UserManagerServiceImpl.class);
    /**
     * 用户DAO.
     */
    @Autowired
    private AgtbUserInfoDAO agtbUserInfoDAO;
    /**
     * 角色DAO.
     */
    @Autowired
    private AgtbRoleInfoDAO agtbRoleInfoDAO;
    /**
     * 用户角色关联关系DAO.
     */
    @Autowired
    private AgtbUserRoleRelDAO agtbUserRoleRelDAO;
    /**
     * 用户自定义配置信息DAO.
     */
    @Autowired
    private AgtbUserConfigrationInfoDAO agtbUserConfigrationInfoDAO;

    /**
     * 组织机构DAO.
     */
    @Autowired
    private AgtbOrganizationInfoDAO agtbOrganizationInfoDAO;

    @Override
    public String queryUserForGrid(final Pager<?> pager) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("service---获得用户dataGrid数据");
        }
        return getGridByHQLNamedQuery("queryUserForGrid", pager);
    }

    @Override
    public String getUserRoles(final String userId) throws Exception {
        UserManageDTO searchModel = new UserManageDTO();
        searchModel.setUserId(userId);
        return getNormalDataBySQLNamedQuery("getUserRoles", searchModel);
    }

    @Override
    public String getUserDetail(final UserManageSearchModel searchModel) throws Exception {
        AgtbUserInfo agtbUserInfo = agtbUserInfoDAO.get(searchModel.getUserId());
        return JSON.toJSONString(JsonUtils.entity2JSONObject(agtbUserInfo, 1));
    }

    @Override
    public JSONObject saveUser(final UserManageDTO userManageDTO) throws Exception {
        String key = userManageDTO.getUserId();
        AgtbOrganizationInfo agtbOrganizationInfo = null;
        if (!StringUtils.isEmpty(userManageDTO.getOrgId())) {
            agtbOrganizationInfo = agtbOrganizationInfoDAO.get(userManageDTO.getOrgId());
        }
        String msgKey = null;
        if (StringUtils.isEmpty(key)) {
            AgtbUserInfo agtbUserInfo = new AgtbUserInfo();
            BeanUtilsEx.copyProperties(agtbUserInfo, userManageDTO);
            key = AgileUtils.getKey();
            agtbUserInfo.setUserId(key);
            agtbUserInfo.setAgtbOrganizationInfo(agtbOrganizationInfo);
            agtbUserInfoDAO.save(agtbUserInfo);
            msgKey = "saveSuccess";
        } else {
            AgtbUserInfo agtbUserInfo = agtbUserInfoDAO.get(key);
            BeanUtilsEx.copyProperties(agtbUserInfo, userManageDTO, true);
            agtbUserInfo.setAgtbOrganizationInfo(agtbOrganizationInfo);
            agtbUserInfoDAO.update(agtbUserInfo);
            msgKey = "updateSuccess";
        }
        JSONObject returnObj = successMsg(msgKey);
        returnObj.put("data", key);
        return returnObj;
    }

    @Override
    public JSONObject deleteUser(final UserManageDTO userManageDTO) throws Exception {
        String key = userManageDTO.getUserId();
        // 校验用户是否含有角色信息,如果已担任角色不能删除,必须先删除角色关联关系.
        boolean have = getBaseDAO().checkIsHave("checkUserRole", userManageDTO);
        if (have) {
            return errorMsg("userDeleteExceptionMsg1");
        }
        boolean haveConfig = getBaseDAO().checkIsHave("checkUserConfig", userManageDTO);
        if (haveConfig) {
            return errorMsg("userDeleteExceptionMsg2");
        }
        agtbUserInfoDAO.deleteByKey(key);
        return successMsg("deleteSuccess");
    }

    @Override
    public JSONObject saveUserRoles(final String userId, final String roles) throws Exception {
        UserManageSearchModel parametersModel = new UserManageSearchModel();
        parametersModel.setUserId(userId);
        // 删除本人原有的关联关系值
        executeDynamicSql("deleteUserRoleRel", parametersModel);
        String msgKey = null;
        if (!StringUtils.isEmpty(roles)) {
            AgtbUserInfo agtbUserInfo = agtbUserInfoDAO.get(userId);
            JSONArray rolesArr = JSONArray.parseArray(roles);
            List<AgtbUserRoleRel> entityList = new ArrayList<AgtbUserRoleRel>();
            for (Object obj : rolesArr) {
                AgtbUserRoleRel agtbUserRoleRel = new AgtbUserRoleRel();
                agtbUserRoleRel.setAgtbUserInfo(agtbUserInfo);
                AgtbRoleInfo agtbRoleInfo = agtbRoleInfoDAO.get(BeanUtilsEx.getProperty(obj, "roleId"));
                agtbUserRoleRel.setAgtbRoleInfo(agtbRoleInfo);
                AgtbUserRoleRelId agtbUserRoleRelId = new AgtbUserRoleRelId();
                agtbUserRoleRelId.setUserId(userId);
                agtbUserRoleRelId.setRoleId(agtbRoleInfo.getRoleId());
                agtbUserRoleRel.setId(agtbUserRoleRelId);
                entityList.add(agtbUserRoleRel);
            }
            agtbUserRoleRelDAO.saveList(entityList);
            msgKey = "userRolesRelUpdateSuccess";
        } else {
            msgKey = "clearUserRolesRelSuccess";
        }
        return successMsg(msgKey);
    }

    @Override
    public JSONObject updateUserPassword(final String userId, final String oldPassword, final String newPassword)
            throws Exception {
        return null;
    }

    @Override
    public JSONObject updateTheme(final String themeId) throws Exception {
        AgtbUserConfigrationInfo agtbUserConfigrationInfo = UserDetailUtils.getUserDetail().getUserInfo()
                .getAgtbUserConfigrationInfo();
        if (agtbUserConfigrationInfo == null) {
            agtbUserConfigrationInfo = new AgtbUserConfigrationInfo();
            agtbUserConfigrationInfo.setThemeName(themeId);
            agtbUserConfigrationInfoDAO.save(agtbUserConfigrationInfo);
        } else {
            agtbUserConfigrationInfo.setThemeName(themeId);
            agtbUserConfigrationInfoDAO.update(agtbUserConfigrationInfo);
        }
        return successMsg("saveSuccess");
    }

    @Override
    public String checkPassword(final String oldPassword) throws Exception {
        String oldPasswordMd5 = AgileUtils.getMD5(oldPassword);
        if (oldPasswordMd5.equals(UserDetailUtils.getUserDetail().getPassword())) {
            return "true";
        }
        return "false";
    }

    @Override
    public JSONObject updatePassword(final UserManageDTO userManageDTO) throws Exception {
        String oldPasswordMd5 = AgileUtils.getMD5(userManageDTO.getLoginPassword());
        if (!oldPasswordMd5.equals(UserDetailUtils.getUserDetail().getPassword())) {
            return errorMsg("unValidPassword");
        } else {
            if (!userManageDTO.getNewPassword().equals(userManageDTO.getNewPasswordConfirm())) {
                return errorMsg("passwordNotMatch");
            } else {
                AgtbUserInfo userInfo = UserDetailUtils.getUserDetail().getUserInfo();
                userInfo.setLoginPassword(AgileUtils.getMD5(userManageDTO.getNewPassword()));
                agtbUserInfoDAO.update(userInfo);
                return successMsg("passwordChangeSuccess");
            }
        }
    }
}
